import { getToken } from './cookie'
import axios from 'axios';
import {  MessageBox,  Message } from 'element-ui';
import Cookies from 'js-cookie'
import store from '@/store'

const DEFAULT_DOMAIN = "http://client.71360.com";
var domainFullUrl = "";
function changeDataType(obj){
  let str = ''
  if(typeof obj == 'object'){
      for(let i in obj){
          if(typeof obj[i] != 'function' && typeof obj[i] != 'object'){
              str += i + '=' + obj[i] + '&' ;
          }else if (typeof obj[i] == 'object'){
              nextStr = '';
              str += changeSonType(i, obj[i])
          }
      }
  }
  return str.replace(/&$/g, '');
}

function changeSonType(objName, objValue){
  if(typeof objValue == 'object'){
      for(let i in objValue){
          if(typeof objValue[i] != 'object'){
              let value = objName + '[' + i + ']=' + objValue[i];
              nextStr += encodeURI(value) + '&';
          }else{
              changeSonType(objName + '[' + i + ']', objValue[i]);
          }
      }
  }
  return nextStr;
}

class Global {
  constructor(name) {
    this.name = name
  }
  getImgUrl(id) {
    return `${process.env.VUE_APP_BASE_API}tcloud-fs/fs/readImage?fileId=${id}&X-Token=${getToken()}`
  }
  setCommonMenu(path, title, parent, icon) {
    var commonMenu = []
    const userId = store.state.user.staffInfo.id
    var commonMenuCookies = Cookies.get('commonMenu' + userId)

    if (commonMenuCookies) commonMenu = JSON.parse(commonMenuCookies)

    if (!commonMenu) commonMenu = []

    var queryMenu = commonMenu.filter(function(i, itemindex) {
      return i.router === path && i.title === title && i.parent === parent && i.icon === icon
    })

    var index = commonMenu.indexOf(queryMenu[0])

    if (index !== -1) commonMenu.splice(index, 1)

    var menu = {
      router: path,
      title: title,
      parent: parent,
      icon: icon
    }

    commonMenu.unshift(menu)

    if (commonMenu.length >= 8) commonMenu = commonMenu.slice(0, 8)

    Cookies.set('commonMenu'  + userId, commonMenu, {
      expires: 7,
      domain: process.env.NODE_ENV === 'development' ? '' : '71360.com'
    })

    return commonMenu
  }
  authenticationStatus(obj) {
    let data = {
      material: true,
      isAgent: false,
      agentType: false
    }
    data = { ...data, ...obj }
    // // 实名认证到期时间
    // authenticationExpireDate
    // // 营业执照到期时间
    // businessLicenseExpireDate

    // // 产品激活状态 -1：未购买 0：未激活 1：已激活
    // productActivationStatus
    // // 实名认证状态 -1： 认证驳回 0： 未认证 1：认证通过 2：即将到期 3：已到期  4：待审核
    // realNameAuthenticationStatus
    // // 营业执照到期状态 0：未到期 1：即将到期 2：已到期
    // businessLicenseStatus
    // // 完善资料认证状态 0：未通过 1：已通过
    // materialStatus
    // // 中文站官网是否上线 0：未上线 1：已上线
    // chineseWebsiteStatus

    // 身份证到期状态 3：未提交 4：即将到期 5：已到期
    // Integer idcardStatus = 3;
    // // 法人身份证到期状态 3：未提交 4：即将到期 5：已到期
    // Integer legalRepreStatus = 3;
    // // 法人身份证到期时间
    // String legalRepreExpireDate = "";
    // // 身份证到期时间
    // String idcardExpireDate = "";
    // // 身份证号
    // String idcard = "";

    //  // 是否分配代理商 0：未分配 1：已分配
    // int agentStatus= 0;
    // // 是否渠道用户 0:渠道 1:直销
    // int channelStatus=0;
    // String agentMobile = "";

    const authencaticationStatus = store.state.user.authencaticationStatus
    if (authencaticationStatus.realNameAuthenticationStatus === 0) {
      const string = '<h4>为保证账号及资产的安全，请先实名认证</h4><p>实名认证决定了账号的归属，部分功能需实名认证后才可使用</p>'
      MessageBox.confirm(string, '提示', {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '立即认证',
        cancelButtonText: '下次再说',
        customClass: 'authentication-container'
      }).then(() => {
        this.goAuthentication()
      })
      return false
    } else if (authencaticationStatus.realNameAuthenticationStatus === 4) {
      const string = `<h4>请先进行实名认证</h4><p>须实名认证审核通过后，才能进行该操作</p>`
      MessageBox.confirm(string, '提示', {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '立即认证',
        cancelButtonText: '取消',
        customClass: 'authentication-container'
      }).then(() => {
        this.goAuthentication()
      })
      return false
    } else if (authencaticationStatus.realNameAuthenticationStatus === -1) {
      const string = `<h4>您提交的实名认证审核未通过，请尽快重新提交</h4><p>实名认证审核未通过，为避免影响您的正常使用，请尽快重新提交</p>`
      MessageBox.confirm(string, '提示', {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '重新认证',
        cancelButtonText: '下次再说',
        customClass: 'authentication-container'
      }).then(() => {
        this.goAuthentication()
      })
      return false
    } else if (authencaticationStatus.realNameAuthenticationStatus === 3) {
      const string = `<h4>实名认证${authencaticationStatus.realNameAuthenticationStatus === 3 ? '已' : '将'}于${authencaticationStatus.authenticationExpireDate}到期,部分功能已暂停使用</h4><p>实名认证中的已到期，为避免影响您的使用，请尽快重新上传！</p>`
      MessageBox.confirm(string, `${authencaticationStatus.realNameAuthenticationStatus === 3 ? '提示' : '提示'}`, {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '立即认证',
        cancelButtonText: '下次再说',
        customClass: 'authentication-container'
      }).then(() => {
        this.goAuthentication()
      })
      return false
    } else if (authencaticationStatus.businessLicenseStatus === 2) {
      const string = `<h4>营业执照${authencaticationStatus.businessLicenseStatus === 2 ? '已' : '将'}于${authencaticationStatus.businessLicenseExpireDate}到期,部分功能已暂停使用</h4><p>实名认证中的营业执照已到期，为避免影响您的使用，请尽快重新上传！</p>`
      MessageBox.confirm(string, `${authencaticationStatus.businessLicenseStatus === 2 ? '提示' : '提示'}`, {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '马上更新',
        cancelButtonText: '下次再说',
        customClass: 'authentication-container'
      }).then(() => {
        this.goAuthentication()
      })
      return false
    } else if (authencaticationStatus.legalRepreStatus === 5) {
      const string = `<h4>法人身份证已于已于${authencaticationStatus.legalRepreExpireDate}到期,部分功能已暂停使用</h4><p>实名认证中的法人身份证已到期，为避免影响您的使用，请尽快重新上传！</p>`
      MessageBox.confirm(string, '提示', {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '重新认证',
        cancelButtonText: '下次再说',
        customClass: 'authentication-container'
      }).then(() => {
        this.goAuthentication()
      })
      return false
    } else if (authencaticationStatus.idcardStatus === 5) {
      const string = `<h4>个人身份证已于${authencaticationStatus.idcardExpireDate}到期,部分功能已暂停使用</h4><p>实名认证中的个人身份证已到期，为避免影响您的使用，请尽快重新上传！</p>`
      MessageBox.confirm(string, '提示', {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '重新认证',
        cancelButtonText: '下次再说',
        customClass: 'authentication-container'
      }).then(() => {
        this.goAuthentication()
      })
      return false
    } else if (authencaticationStatus.materialStatus === 0 && data.material) {
      const string = `<h4>您还未完善推广资料，暂不能使用该服务</h4><p>推广资料是企业基本信息，使用所有推广服务时，需用到企业的基本信息，请尽快完善</p>`
      MessageBox.confirm(string, `提示`, {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '立即完善',
        cancelButtonText: '下次再说',
        customClass: 'authentication-container'
      }).then(() => {
        this.complateData()
      })
      return false
    } else if (authencaticationStatus.agentStatus === 0 && data.isAgent) {
      const string = `<p>账号未划分区域，暂不支持购购买，请联系客服处理</p>`
      MessageBox.confirm(string, `提示`, {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '我知道了',
        showCancelButton: false,
        customClass: 'authentication-container'
      })
      return false
    } else if (authencaticationStatus.channelStatus === 0 && data.agentType) {
      const string = `<p>很抱歉！当前不能使用充值功能，请联系您的代理商 <i style="color:#409EFF ">${authencaticationStatus.agentMobile}</i> </p>`
      MessageBox.confirm(string, `提示`, {
        dangerouslyUseHTMLString: true,
        showCancelButton: false,
        type: 'warning',
        confirmButtonText: '我知道了',
        customClass: 'authentication-container'
      })
      return false
    } else {
      return true
    }
  }
  goAuthentication() {
    window.location.href = process.env.VUE_APP_7_OPEN + 'userCenter/authentication/fastAuthentication'
  }
  dateFormate(date) {
    let month = date.getMonth()
    let day = date.getDate()

    if (month < 9) {
      month = '0' + (month + 1)
    } else {
      month = month + 1
    }
    if (day < 10) {
      day = '0' + day
    }
    return date.getFullYear() + '-' + month + '-' + day
  }
  getApiUrl() {
    var url = DEFAULT_DOMAIN;

    if (domainFullUrl != "") {
      url = domainFullUrl;
    } else if (window.CefJS) {
      domainFullUrl = CefJS.getDomainUrl()
      if (domainFullUrl)
        url = domainFullUrl;
    }

    return url;
  }
  tyunPost(url, postData) {
    var postUrl = this.getApiUrl() + url;

    postData = this.addTicketInfo(postData);

    var ticketInfo = {};

    if (window.CefJS)
      ticketInfo = JSON.parse(CefJS.getTicketInfo());

    return axios({
      url: postUrl,
      method: "POST",
      // data: $.param(postData),
      data: changeDataType(postData),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        //dev环境注释掉其他头部信息 不然post会变成options请求
        //'Ticket': ticketInfo.Ticket,
        //'Timestamp': ticketInfo.Timestamp,
        //'Token': ticketInfo.Token,
        //'AppVersion': ticketInfo.AppVersion,
        //'ServerVersion': ticketInfo.ServerVersion
      }
    });
  }
  getUploadUrl() {
    return this.getApiUrl();
  }
  addTicketInfo(postData) {
    var ticketInfo = this.getTicketInfo();

    if (!postData) postData = {};

    postData.ticket = ticketInfo.Ticket;

    //postData.timestamp = ticketInfo.Timestamp;

    //postData.token = ticketInfo.Token;

    return postData;
  }
  getTicketInfo() {
    var ticketInfo = {};

    if (window.CefJS)
      ticketInfo = JSON.parse(CefJS.getTicketInfo());

    //请在这里填写你的测试票据信息
    var devTicket = '22222222-df14-49be-a58a-63edb0b96d75';

    ticketInfo.Ticket = ticketInfo.Ticket ? ticketInfo.Ticket : devTicket;

    return ticketInfo;
  }
  openMessageBox(message, type = "error", onCloseMethod = null) {
    return Message({
      message: message,
      showClose: true,
      type: type,
      onClose: onCloseMethod,
      duration: 2000,
    });
  }
  openConfirmBox(message, type = "warning", title = "提示") {
    var myMessageBtn = getButtonColor();
    return MessageBox.confirm(message, title, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      cancelButtonClass: myMessageBtn.cancel,
      confirmButtonClass: myMessageBtn.confirm,
      type: type
    });
  }
  openAlertBox(message, type = "info", title = "提示") {
    var myMessageBtn = getButtonColor();
    return MessageBox.alert(message, title, {
      confirmButtonText: "确定",
      confirmButtonClass: myMessageBtn.confirm,
      type: type
    });
  }
  parseTime (time, cFormat) {
    if (arguments.length === 0) {
      return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
      date = time
    } else {
      if (('' + time).length === 10) time = parseInt(time) * 1000
      date = new Date(time)
    }
    const formatObj = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds(),
      a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
      let value = formatObj[key]
      if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
      if (result.length > 0 && value < 10) {
        value = '0' + value
      }
      return value || 0
    })
    return time_str
  }
  // 获取本周
  getStartWeek(){
    let oneDayLong = 24*60*60*1000 ;
    let now = new Date();
    let mondayTime = now.getTime() - (now.getDay()-1)*oneDayLong;
    let monday = new Date(mondayTime);
    var start= this.dateFormate(monday)
    return start;
  }
  getEndWeek(){
    let oneDayLong = 24*60*60*1000 ;
    let now = new Date();
    let sundayTime = now.getTime() + (7-now.getDay())*oneDayLong;
    let sunday = new Date(sundayTime);
    var end= this.dateFormate(sunday)
    return end;
  }
/**
   *获得本月的开始日期和结束日期
   */
  getStartMonth() {
    let oneDayLong = 24*60*60*1000;
    let now = new Date();
    let year = now.getFullYear();
    let monthStartDate = new Date(year, now.getMonth(), 1);//当前月1号
    var start=this.dateFormate(monthStartDate)
    return start;
  }
  getEndMonth() {
    let oneDayLong = 24*60*60*1000;
    let now = new Date();
    let year = now.getFullYear();
    let monthStartDate = new Date(year, now.getMonth(), 1);//当前月1号
    let nextMonthStartDate = new Date(year, now.getMonth()+1, 1);//下个月1号
    let days = (nextMonthStartDate.getTime() - monthStartDate.getTime())/oneDayLong;//计算当前月份的天数
    let monthEndDate = new Date(year, now.getMonth(), days);
    var End=this.dateFormate(monthEndDate)
    return End;
  }

  formErrorScroll() { // 报错回到第一个错误的地方
    if (document.querySelector('.el-form-item__error')) {
      document
        .querySelector('.el-form-item__error')
        .parentNode.scrollIntoView({
          block: 'start',
          behavior: 'smooth'
        })
    }
  }
}
export default Global

/*
* 获取最近几天日期 getDay(0);//当天日期 getDay(-7);//7天前日期 getDay(3);//3天后日期
*
* */
export function getDay(day) {
  let today = new Date();
  let targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
  today.setTime(targetday_milliseconds); //注意，这行是关键代码

  let tYear = today.getFullYear();
  let tMonth = today.getMonth();
  let tDate = today.getDate();
  tMonth = doHandleMonth(tMonth + 1);
  tDate = doHandleMonth(tDate);
  return tYear+"-"+tMonth+"-"+tDate;
}

function doHandleMonth(month){
  var m = month;
  if(month.toString().length === 1){
    m = "0" + month;
  }
  return m;
}

/**
 * 计算2个日期相差的天数，不包含今天，如：2016-12-13到2016-12-15，相差2天
 * @param startDateString
 * @param endDateString
 * @returns
 */
export function dateDiff(startDateString, endDateString){
  var separator = "-"; //日期分隔符
  var startDates = startDateString.split(separator);
  var endDates = endDateString.split(separator);
  var startDate = new Date(startDates[0], startDates[1]-1, startDates[2]);
  var endDate = new Date(endDates[0], endDates[1]-1, endDates[2]);
  return parseInt(Math.abs(endDate - startDate ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
}

/**
 * 字符串日期相减，不包含今天，如：2016-12-13到2016-12-15，相差2天
 * @param startDateString
 * @param endDateString
 * @returns
 */
export function dateSubtraction(startDateString, endDateString){
  var separator = "-"; //日期分隔符
  var startDates = startDateString.split(separator);
  var endDates = endDateString.split(separator);
  var startDate = new Date(startDates[0], startDates[1]-1, startDates[2]);
  var endDate = new Date(endDates[0], endDates[1]-1, endDates[2]);
  return parseInt((endDate - startDate) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数
}

/**
 * 本月、上月、下月的起始、结束日期
 * getMonth(type,months)  //type为字符串类型，有两种选择，"s"代表开始,"e"代表结束，months为数字类型，不传或0代表本月，-1代表上月，1代表下月
 * getMonth("s",1)  //得到下月第一天的yyyy-mm-dd格式日期
 * getMonth("e",1)  //得到下月最后一天的yyyy-mm-dd格式日期
 */
export function getMonthStartAndEndDate(type, months) {
  var d = new Date();
  var year = d.getFullYear();
  var month = d.getMonth() + 1;
  if (Math.abs(months) > 12) {
    months = months % 12;
  }
  if (months !== 0) {
    if (month + months > 12) {
      year++;
      month = (month + months) % 12;
    } else if (month + months < 1) {
      year--;
      month = 12 + month + months;
    } else {
      month = month + months;
    }
  }
  month = month < 10 ? "0" + month: month;
  var date = d.getDate();
  var firstday = year + "-" + month + "-" + "01";
  var lastday = "";
  if (month === "01" || month === "03" || month === "05" || month === "07" || month === "08" || month === "10" || month === "12") {
    lastday = year + "-" + month + "-" + 31;
  } else if (month === "02") {
    if ((year % 4 === 0 && year % 100 !== 0) || (year % 100 === 0 && year % 400 === 0)) {
      lastday = year + "-" + month + "-" + 29;
    } else {
      lastday = year + "-" + month + "-" + 28;
    }
  } else {
    lastday = year + "-" + month + "-" + 30;
  }
  var day = "";
  if (type === "s") {
    day = firstday;
  } else {
    day = lastday;
  }
  return day;
}
/* 时时间戳转为字符串*/
export function parseTime (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

